package com.hy.mvc.web.inteceptor;

import com.hy.mvc.web.conroller.UserController;
import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <pre>
 *    author  : Booker
 *    time    : 2017/12/7 10:21
 *    desc    : 登陆时日志检查
 *    version : v1.0
 * </pre>
 */
public class LogInterceptor implements HandlerInterceptor {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        request.setAttribute("startTime",System.currentTimeMillis());
        logger.info("URL:" + request.getRequestURI());
        logger.info("Method:" + request.getMethod());
        logger.info("Remote Ip:" + request.getRemoteAddr());
        logger.info("QueryString:" + request.getQueryString());
        logger.info("ContextPath:" + request.getContextPath());

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Long endTime = System.currentTimeMillis();
        logger.info("计算时间为:" + (endTime - (Long) request.getAttribute("startTime")) + "ms");
    }
}
